package org.asg.dis.controller;

import org.asg.dis.model.ApiResponse;
import org.asg.dis.model.Shipment;
import org.asg.dis.model.ShipmentStatus;
import org.asg.dis.request.ConfirmShipmentReq;
import org.asg.dis.request.ModifyShipmentReq;
import org.asg.dis.service.ShipmentService;
import org.asg.dis.service.TraceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;
import java.util.UUID;

@RestController
public class CourierController {
    private final ShipmentService shipmentService;
    private final TraceService traceService;
    @Autowired
    public CourierController(ShipmentService shipmentService, TraceService traceService) {
        this.shipmentService = shipmentService;
        this.traceService = traceService;
    }

    @PostMapping("/courier/confirm")
    @PreAuthorize("hasRole('Courier')")
    public ApiResponse<String> confirmShipment(@RequestBody ConfirmShipmentReq request){
        Optional<Shipment> shipmentOpt = shipmentService.getShipmentById(request.shipmentId());
        if(shipmentOpt.isPresent()){
            Shipment shipment = shipmentOpt.get();
            BeanUtils.copyProperties(request, shipment);
            shipmentService.updateShipment(UUID.fromString(request.shipmentId()), shipment);
            //TODO 发消息
            traceService.createTrace(shipment, ShipmentStatus.已接收, request.location(), "快递员揽收");
            return ApiResponse.ok();
        } else {
            return ApiResponse.error(HttpStatus.BAD_REQUEST.value(), "no shipment");
        }
    }

    @GetMapping("/courier/query")
    @PreAuthorize("hasRole('Courier')")
    public ApiResponse<?> queryShipment(@RequestParam String shipmentId){
        Optional<Shipment> shipmentOpt = shipmentService.getShipmentById(shipmentId);
        if(shipmentOpt.isPresent()){
            return ApiResponse.ok(shipmentOpt.get());
        }else{
            return ApiResponse.notFound("no shipment");
        }
    }

    @GetMapping("/courier/modifyShipment")
    @PreAuthorize("hasRole('Courier')")
    public ApiResponse<String> modifyShipment(@RequestBody ModifyShipmentReq request){
        Optional<Shipment> shipmentOpt = shipmentService.getShipmentById(request.shipmentId());
        if(shipmentOpt.isPresent()){
            Shipment shipment = shipmentOpt.get();
            BeanUtils.copyProperties(request, shipment);
            shipmentService.updateShipment(UUID.fromString(request.shipmentId()), shipment);
            //TODO 发消息
            // 更新轨迹
            traceService.createTrace(shipment, ShipmentStatus.已接收, request.location(), "快递员揽收");
            return ApiResponse.ok();
        } else {
            return ApiResponse.error(HttpStatus.BAD_REQUEST.value(), "no shipment");
        }
    }


}
